package com.seeyoui.kensite.framework.file.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class ChangeFileEncoding {
    public static int fileCount = 0;
    public static String sourceCharset = "GBK"; // 源文件编码
    public static String targetCharset = "utf8"; // 目标文件编码
    public static void convert(String filePath) throws IOException {
        File file = new File(filePath);
        // 如果是文件则进行编码转换，写入覆盖原文件
        if (file.isFile()) {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(
                    file), sourceCharset);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                // 注意写入换行符
                line =  URLEncoder.encode(line, "utf8");
                sb.append(line + "\r\n");//windows 平台下 换行符为 \r\n
            }
            br.close();
            isr.close();

            File targetFile = new File(file.getPath());
            OutputStreamWriter osw = new OutputStreamWriter(
                    new FileOutputStream(targetFile), targetCharset);
            BufferedWriter bw = new BufferedWriter(osw);
            // 以字符串的形式一次性写入
            bw.write(URLDecoder.decode(sb.toString(), "utf8"));
            bw.close();
            osw.close();
            fileCount++;
        }
    }
}